package com.kittyhawks.bksystem.weixin.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.kittyhawks.bksystem.entity.User;
import com.kittyhawks.bksystem.service.UserService;
import com.kittyhawks.bksystem.weixin.controller.Base;
import com.kittyhawks.bksystem.weixin.dto.WeiXinAuthorizeDTO;
import com.kittyhawks.bksystem.weixin.dto.WeiXinUserInfoDTO;
import com.kittyhawks.bksystem.weixin.service.WeChatAuthService;
import com.kittyhawks.bksystem.weixin.util.WeiXinFinalValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by VS on 2018/4/10.
 */
@Component
public class WeixinLoginInterceptor implements HandlerInterceptor {

    @Autowired
    private WeChatAuthService weiXinUserService;

    @Autowired
    private UserService userService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        HttpSession httpSession=request.getSession();

        /*User u = new User();
        u.setId("oABjS06WQxFyseYL9ffZzavPxbPk");
        u.setAvatar("http://thirdwx.qlogo.cn/mmopen/vi_32/Q3auHgzwzM7ubrSXIXXHibWrZtbI8yEWpQqYcaZqGhzcMU756aWWQQZR67kqcc3U7pe3ztXatMUqsFI5Q8vYKWw/132");
        httpSession.setAttribute(WeiXinFinalValue.WX_SESSION_USER,u);*/

        User userInfo=(User) httpSession.getAttribute(WeiXinFinalValue.WX_SESSION_USER);
        if(Base.empty(userInfo)){
            String agent = request.getHeader("User-Agent");
            if(null!=agent&&agent.toLowerCase().indexOf("micromessenger")>=0) { //如果是微信客户端打开  我们才进行授权处理
                String code=request.getParameter("code");
                String state=request.getParameter("state");
                System.out.println("code = "+code+"  state= "+state);
                if(Base.notEmpty(code)&&Base.notEmpty(state)&&state.equals("1")){ //通过Code获取openid来进行授权
                    try {
                        String resContent = weiXinUserService.getAccessToken(code);
                        System.out.println("【微信用户Token信息】========>>>>>>>"+resContent);
                        WeiXinAuthorizeDTO weiXinAuthorizeDTO= JSONObject.parseObject(resContent,WeiXinAuthorizeDTO.class);
                        if(Base.notEmpty(weiXinAuthorizeDTO)){
                            User user = userService.selectByPrimaryKeyPro(weiXinAuthorizeDTO.getOpenid());
                            if(user != null && user.getId()!=null){
                                httpSession.setAttribute(WeiXinFinalValue.WX_SESSION_USER, user);
                                return true;
                            }
                            JSONObject jsonobject = weiXinUserService.getUserInfo(weiXinAuthorizeDTO.getAccess_token(),weiXinAuthorizeDTO.getOpenid());
                            System.out.println("【微信用户信息】========>>>>>>>"+jsonobject);
                            WeiXinUserInfoDTO weiXinUserInfoDTO = JSONObject.parseObject(jsonobject.toJSONString(),WeiXinUserInfoDTO.class);
                            user = new User();
                            user.setId(weiXinUserInfoDTO.getOpenid());
                            user.setNickname(weiXinUserInfoDTO.getNickname());
                            user.setAvatar(weiXinUserInfoDTO.getHeadimgurl());
                            user.setSex(Integer.parseInt(weiXinUserInfoDTO.getSex()));
                            userService.insertSelective(user);
                            httpSession.setAttribute(WeiXinFinalValue.WX_SESSION_USER, user);
                            return true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else{
                    /**
                     * 用户同意授权后 ，页面将跳转至 redirect_uri/?code=CODE&state=STATE。若用户禁止授权，则重定向后不会带上code参数，
                     * 仅会带上state参数redirect_uri?state=STATE
                     * 把请求提交给微信  而不是使用 httpClient进行get提交url不然会提示请使用微信客户端打开
                     * 当我 们吧这个url提交给微信客户端之后 那么微信又会吧这个url再返回给我并且带回code参数  所以第一次访问时code、state是为null的
                     */

                    String redirectURL=request.getRequestURL().toString();
                    String queryparam=request.getQueryString();

                    System.out.println("code:"+code+"------>"+"state:"+state);
                    if(Base.notEmpty(queryparam)){
                        redirectURL=redirectURL+"?"+queryparam;//重定向url
                    }
                    String url=WeiXinFinalValue.WX_AUTHORIZE;
                    url = url.replace("APPID",WeiXinFinalValue.APPID).replace("REDIRECT_URI",
                            java.net.URLEncoder.encode(redirectURL, "UTF-8")//重定向url必须经过 URLEncoder编码
                    ).replace("SCOPE", WeiXinFinalValue.SNSAPI_INFO).replace("STATE", "1");

                    response.sendRedirect(url);
                    System.out.println("【微信授权url】=======>>>>>"+url);
                    //url = "#";//进首页
                    //response.sendRedirect(url);
                    return false;
                }
                return false;
            }
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
